<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/12/10
 * Time: 11:36
 */
require('../vendor/autoload.php');
require('../define.php');
require('util/WechatPlatform.php');

use  \wechat\util\WechatPlatform;

$post = file_get_contents('php://input');
$encode_ticket = isimplexml_load_string($post, 'SimpleXMLElement', LIBXML_NOCDATA);
if (empty($post) || empty($encode_ticket)) {
    exit('fail');
}
$decode_ticket = aes_decode($encode_ticket->Encrypt, WechatPlatform::getOpenPlatformInstance()['config']['aes_key']);
$ticket_xml = isimplexml_load_string($decode_ticket, 'SimpleXMLElement', LIBXML_NOCDATA);
if (empty($ticket_xml)) {
    exit('fail');
}

if (!empty($ticket_xml->ComponentVerifyTicket) && $ticket_xml->InfoType == 'component_verify_ticket') {
    $componet_verify_ticket = 'easywechat.open_platform.verify_ticket.' .WechatPlatform::getOpenPlatformInstance()['config']['app_id'];
    WechatPlatform::getOpenPlatformInstance()['cache']->set($componet_verify_ticket, strval($ticket_xml->ComponentVerifyTicket));
}

function aes_decode($message, $encodingaeskey = '', $appid = '')
{
    $key = base64_decode($encodingaeskey . '=');
    $ciphertext_dec = base64_decode($message);
    $module = mcrypt_module_open(MCRYPT_RIJNDAEL_128, '', MCRYPT_MODE_CBC, '');
    $iv = substr($key, 0, 16);

    mcrypt_generic_init($module, $key, $iv);
    $decrypted = mdecrypt_generic($module, $ciphertext_dec);
    mcrypt_generic_deinit($module);
    mcrypt_module_close($module);
    $block_size = 32;

    $pad = ord(substr($decrypted, -1));
    if ($pad < 1 || $pad > 32) {
        $pad = 0;
    }
    $result = substr($decrypted, 0, (strlen($decrypted) - $pad));
    if (strlen($result) < 16) {
        return '';
    }
    $content = substr($result, 16, strlen($result));
    $len_list = unpack("N", substr($content, 0, 4));
    $contentlen = $len_list[1];
    $content = substr($content, 4, $contentlen);
    $from_appid = substr($content, $xml_len + 4);
    if (!empty($appid) && $appid != $from_appid) {
        return '';
    }
    return $content;
}

function isimplexml_load_string($string, $class_name = 'SimpleXMLElement', $options = 0, $ns = '', $is_prefix = false)
{
    libxml_disable_entity_loader(true);
    if (preg_match('/(\<\!DOCTYPE|\<\!ENTITY)/i', $string)) {
        return false;
    }
    return simplexml_load_string($string, $class_name, $options, $ns, $is_prefix);
}